package com.xiaobawang.knowledge.spider.service.impl;

import com.xiaobawang.knowledge.spider.config.EmailConfig;
import com.xiaobawang.knowledge.spider.exception.BusinessException;
import com.xiaobawang.knowledge.spider.model.dto.EmailDTO;
import com.xiaobawang.knowledge.spider.service.EmailService;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.io.File;

/**
 * @author synhard
 * @description 邮箱服务实现类
 * @date 2024/2/1 13:30
 * @email songxinhang2023@e-chinalife.com
 * @id 18101119
 * @phone 13001321080
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;

    private final EmailConfig emailConfig;

    public EmailServiceImpl(JavaMailSender mailSender,
                            EmailConfig emailConfig) {
        this.mailSender = mailSender;
        this.emailConfig = emailConfig;
    }

    @Override
    public void sendEmail(@Valid EmailDTO emailDTO) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(emailDTO.getTo());
            helper.setFrom(emailDTO.getFrom());
            helper.setSubject(emailDTO.getSubject());
            helper.setText("", emailDTO.getContent());
            File attachment = emailDTO.getFile();
            if (attachment != null) {
                helper.addAttachment(attachment.getName(), attachment);
            }
            mailSender.send(message);
            log.info("发送邮件成功!");
        } catch (Exception e) {
            log.error("发送邮件时出错：{}", e.getMessage());
            throw new BusinessException("发送邮件时出错");
        }
    }

    @Override
    public void sendErrEmail() {
        EmailDTO emailItem = new EmailDTO();
        emailItem.setSubject("异常通知");
        emailItem.setContent("爬取每日金融监管处罚文件异常，请及时排查！");
        emailItem.setFrom(emailConfig.getFrom());
        // 收件人
        emailItem.setTo(emailConfig.getErrorReceiver());
        this.sendEmail(emailItem);
    }
}
